from abc import ABC, abstractmethod
import time
import requests
from tools.myjwt import mjwt
from user.models import ThirdPartyLoginModel, UserModel


# 抽象产品类
class Product(ABC):
    @abstractmethod
    def get_url(self):
        pass

    @abstractmethod
    def callback(self, request):
        pass


# 具体产品类
class Dingding(Product):
    def __init__(self) -> None:
        self.redicturl = "http://127.0.0.1:8000/user/dingtalkApi/"
        self.cid = "dingrltwa45dmbxvnqn3"
        self.url = "https://login.dingtalk.com/oauth2/auth?redirect_uri=%s&response_type=code&client_id=%s&scope=openid&state=dddd&prompt=consent"

    def get_url(self):
        url = self.url % (self.redicturl, self.cid)
        return url

    def callback(self, request):
        # 获取code
        authCode = request.query_params.get('code')
        # 根据authCode获取用户accessToken
        data = {
            "clientId": "dingrltwa45dmbxvnqn3",
            "clientSecret": "Zf5iiTpNNPTF43lNR2TWV97BwkpAjY1kAXCu-2i6dBo6za6FmwZpjdk6xvY5sUu6",
            "code": authCode,
            "grantType": "authorization_code"
        }
        resp = requests.post('https://api.dingtalk.com/v1.0/oauth2/userAccessToken', json=data).json()
        accessToken = resp.get('accessToken')

        # 根据accessToken获取用户信息
        headers = {"x-acs-dingtalk-access-token": accessToken}
        resp = requests.get('https://api.dingtalk.com/v1.0/contact/users/me', headers=headers).json()
        name = resp.get('nick')
        uid = resp.get('openId')
        phone = resp.get('mobile')
        print(name)
        print(uid)
        print(phone)
        # 三方登录表查询
        thir_party_login = ThirdPartyLoginModel.objects.filter(uid=uid).first()
        # print('-------')
        # print(thiry_party_login.py)
        # userid = thiry_party_login.py.user
        # 判断uid是否存在 不存在则添加到用户表和三方登录表中
        # 如果不存在，用mobile写入用户表，再把uid和userid写入第三方登录表
        if thir_party_login:
            user = thir_party_login.user
            print('-------')
            print(user)
        else:
            user = UserModel.objects.create(mobile=phone, nikename=name)
            ThirdPartyLoginModel.objects.create(user=user, uid=uid, type='dingding')
            # 生成token
        data = {"userid": user.id, 'time': int(time.time())}
        token = mjwt.jwt_encode(data)
        url = "http://localhost:8080/#/updatetoken?token=" + str(token) + "&userid=" + str(user.id)
        # 把token和userid传给前端
        return url


class QQ(Product):
    def get_url(self):
        return "https://www.qq.com"

    def callback(self, request):
        return "QQ Callback"


class Weixin(Product):
    def get_url(self):
        return "https://www.weixin.qq.com"

    def callback(self, request):
        return "Weixin Callback"


# 工厂类
class ProductFactory:
    def create_product(self, product_type):
        if product_type == "dingding":
            return Dingding()
        elif product_type == "qq":
            return QQ()
        elif product_type == "weixin":
            return Weixin()
        else:
            raise ValueError("无效的产品类型")


